package io.chenglicun.modules.clc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.chenglicun.common.page.PageData;
import io.chenglicun.common.service.impl.CrudServiceImpl;
import io.chenglicun.common.constant.Constant;
import io.chenglicun.modules.clc.dao.ClcQuestionBankDao;
import io.chenglicun.modules.clc.dto.ClcQuestionBankDTO;
import io.chenglicun.modules.clc.dto.ClcQuestionDTO;
import io.chenglicun.modules.clc.entity.ClcQuestionBankEntity;
import io.chenglicun.modules.clc.service.ClcQuestionBankService;
import io.chenglicun.modules.clc.service.ClcQuestionService;
import io.chenglicun.modules.security.user.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 题库管理
 *
 * @author HB 137664951@qq.com
 * @since 1.0 2023-10-18
 */
@Service
public class ClcQuestionBankServiceImpl extends CrudServiceImpl<ClcQuestionBankDao, ClcQuestionBankEntity, ClcQuestionBankDTO> implements ClcQuestionBankService {

    @Autowired
    private ClcQuestionService clcQuestionService;

    @Override
    public QueryWrapper<ClcQuestionBankEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<ClcQuestionBankEntity> wrapper = new QueryWrapper<>();


        return wrapper;
    }

    @Override
    public PageData<ClcQuestionBankDTO> page(Map<String, Object> params) {
        PageData<ClcQuestionBankDTO> page = super.page(params);
        List<ClcQuestionBankDTO> list = page.getList();
        setData(list.toArray(new ClcQuestionBankDTO[0]));
        return page;
    }

    @Override
    public List<ClcQuestionBankDTO> list(Map<String, Object> params) {
        List<ClcQuestionBankDTO> list = super.list(params);
        setData(list.toArray(new ClcQuestionBankDTO[0]));
        return list;
    }

    @Override
    public ClcQuestionBankDTO get(Long id) {
        ClcQuestionBankDTO dto = super.get(id);
        setData(dto);
        return dto;
    }

    private void setData(ClcQuestionBankDTO... dtos) {
        if (dtos == null || dtos.length == 0) return;
        Long[] bankIds = Arrays.stream(dtos).map(ClcQuestionBankDTO::getId).filter(Objects::nonNull).toArray(Long[]::new);

        List<ClcQuestionDTO> questionDTOS = bankIds.length == 0 ? new ArrayList<>() : clcQuestionService.getByBankIds(bankIds);

        for (ClcQuestionBankDTO dto : dtos) {
            int sum = questionDTOS.stream().filter(t -> t.getBankId().equals(dto.getId())).mapToInt(ClcQuestionDTO::getScore).sum();
            dto.setScore(sum);
        }
    }
}